package com.weiz.domain.excel;

import com.alibaba.excel.converters.Converter;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateOnlyConverter implements Converter<Date> {
    public static final TimeZone TIME_ZONE_DEFAULT = TimeZone.getTimeZone("Asia/Shanghai");
    private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = ThreadLocal.withInitial(() -> {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        sdf.setTimeZone(TIME_ZONE_DEFAULT); // 设置为 UTC 或者其他所需时区
        return sdf;
    });

//    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public Class<Date> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public WriteCellData convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return new WriteCellData();
        }
        return new WriteCellData(DATE_FORMAT.get().format(value));
    }

    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (cellData == null) {
            return null;
        }
        // 检查是否是数字类型
        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            BigDecimal numberValue = cellData.getNumberValue();
            if (numberValue != null) {
                return fromExcelSerialDate(numberValue.doubleValue());
            }
        } else if (cellData.getType() == CellDataTypeEnum.STRING) {
            String stringValue = cellData.getStringValue();
            if (stringValue != null && !stringValue.trim().isEmpty()) {
                try {
                    return DATE_FORMAT.get().parse(stringValue.trim());
                } catch (ParseException e) {
                    // 处理解析异常，可以记录日志或抛出自定义异常
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private Date fromExcelSerialDate(Double serialDate) {
        Calendar calendar = Calendar.getInstance(TIME_ZONE_DEFAULT); // 设置为北京时区
        // Excel 序列号从 1900-01-01 开始，但需要注意的是，Excel 认为 1900-02-29 是存在的（实际上不存在），所以我们需要减去这一天
        calendar.set(1899, Calendar.DECEMBER, 30); // 设置为 1899-12-30
        // 只取整数部分作为天数，忽略小数部分（即时间）
        int days = serialDate.intValue();
        calendar.add(Calendar.DAY_OF_MONTH, days);
        // 清除时间部分
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
}